<template>
  <div class="costDoc">
    <div class="topbar" key="cd">
      <p>类型显示</p>
      <el-select v-model="showType" @change="searchCost">
        <el-option
          v-for="item in showTypeList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <p>品牌</p>
      <el-select v-model="brandedName">
        <el-option
          v-for="item in brandedNameList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <!-- <el-input v-model="brandedName" key="cost1"></el-input> -->
      <p>款号</p>
      <el-input v-model="styleNumber" key="cost2"></el-input>
      <p>品名</p>
      <el-select v-model="commodityName" filterable>
        <el-option
          v-for="item in commodityNameList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <!-- <el-input v-model="commodityName" key="cost3"></el-input> -->
      <p>类型</p>
      <el-select v-model="type" clearable>
        <el-option
          v-for="item in typeList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          :disabled="item.disabled"
        >
        </el-option>
      </el-select>
      <p>折数</p>
      <el-input
        v-model="discount"
        key="cost4"
        :disabled="type != '折数' || type == ''"
        @keyup.enter.native="save"
      ></el-input>
      <p>定价</p>
      <el-input
        style="margin-right: 150px"
        v-model="sellingPrice"
        key="cost5"
        :disabled="type == '折数' || type == ''"
        @keyup.enter.native="save"
      ></el-input>
      <!-- 新增 -->
      <p>是否新款</p>
      <el-select v-model="newStyleNumber">
        <el-option
          v-for="item in newStyleLits"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <p>季度</p>
      <el-select v-model="quarterName" @change="changeQuarterName">
        <el-option
          v-for="(item, _index) in quarterList"
          :key="_index"
          :label="item.name"
          :value="_index"
        >
        </el-option>
      </el-select>
    </div>
    <div class="operation">
      <el-button type="primary" icon="el-icon-search" @click="searchCost"
        >查询</el-button
      >
      <el-button icon="el-icon-folder-checked" @click="save">保存</el-button>

      <el-tooltip
        class="item"
        effect="dark"
        content="说明：更新厂进退表的单价和金额"
        placement="right"
      >
        <el-button icon="el-icon-refresh-left" @click="refresh">更新</el-button>
      </el-tooltip>

      <i class="el-icon-question" key="costI"></i>
      <p>温馨提示：更新按钮是更新厂进退表的单价和金额</p>
    </div>

    <el-table
      :data="showList"
      style="width: 100%"
      height="75vh"
      highlight-current-row
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
      @row-click="rowClick"
    >
      <el-table-column :prop="tableProp" :label="tableLabel" width="180">
      </el-table-column>
      <el-table-column prop="sellingPrice" label="售价￥" width="180">
      </el-table-column>
      <el-table-column prop="price_usd" label="售价$" width="180">
      </el-table-column>
      <el-table-column prop="costOne" label="成本￥" width="180">
        <template slot-scope="scope">
          <el-input
            size="small"
            v-model="scope.row.costOne"
            @blur="
              handleInputBlurResult($event, {
                index: scope.$index,
                key: 'costOne',
                result: scope.row['costOne'],
                row: scope.row
              })
            "
          >
          </el-input>
        </template>
      </el-table-column>
      <el-table-column prop="discount" label="厂进折数" width="180">
      </el-table-column>
      <el-table-column prop="brandedName" label="品牌" width="180">
      </el-table-column>
      <el-table-column prop="quarterName" label="季度"> </el-table-column>
      <el-table-column prop="newStyleNumber" label="是否新款">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.newStyleNumber"
            active-color="#017afe"
            inactive-color="#dcdfe6"
            disabled
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </template>
      </el-table-column>
    </el-table>

    <foot-view
      class="footView"
      :pagesNum="pagesNum"
      :hasPagination="true"
      :pageSize="limit"
      :tableTypeChange="tableTypeChange"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
      <div slot="text">
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>
  </div>
</template>

<script>
import {
  getCost,
  putCostSave,
  putCostUpdate,
  getQuarter
} from '../../../network/cost'
import { getCommodityName } from '../../../network/commodity'
import { getBranded } from '../../../network/branded'
import { getArtNo } from '../../../network/artNo'

import footView from '../../../components/FootView'

import enterUp from '../../../components/mixins/enterUp'

export default {
  name: 'cost_doc',
  mixins: [enterUp],
  data() {
    return {
      inpList: [],
      showType: '1',
      showTypeList: [
        {
          label: '以款号',
          value: '1'
        },
        {
          label: '以货号',
          value: '2'
        }
        // ,{
        //   label: '以品名',
        //   value: '3'
        // }
      ],
      tableLabel: '款号',
      tableProp: 'styleNumber',
      brandedName: '',
      brandedNameList: [],
      styleNumber: '',
      commodityName: '',
      commodityNameList: [],
      type: '定价',
      typeList: [
        {
          label: '定价',
          value: '定价'
        },
        {
          label: '单款',
          value: '单款',
          disabled: false
        },
        {
          label: '折数',
          value: '折数'
        }
      ],
      discount: '',
      sellingPrice: '',
      costList: [],
      showList: [],
      kindsNumber: '',
      params: [],

      // jxQuarter: document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))[1],
      jxQuarter: null,

      // 总数据条数
      dataLen: 0,
      // 总页码
      pagesNum: 0,
      // 分页条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      tableTypeChange: false,
      // 以下新增
      newStyleLits: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ],
      newStyleNumber: null,
      quarterList: [],
      quarter: null,
      quarterName: ''
    }
  },
  watch: {
    dataLen(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    },
    limit(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    },
    styleNumber(a, b) {
      this.styleNumber = a.toUpperCase().trim()
    },
    showType(a, b) {
      if (a == '2') {
        this.typeList[1].disabled = false
      } else {
        this.typeList[1].disabled = true
      }
    }
  },
  created() {
    this._getCost()
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
  },
  components: {
    footView
  },
  methods: {
    searchCost() {
      this.currentPage = 1
      this.tableTypeChange = !this.tableTypeChange
      this._getCost()
    },

    rowClick(e) {
      this.params = [e]
    },

    save() {
      let r = /^[0-9]+.?[0-9]*/
      if (this.type == '折数') {
        if (!String(this.discount)) {
          this.$message({
            type: 'warning',
            offset: 400,
            message: '折数不能为空'
          })
          return
        }
        if (!r.test(this.discount)) {
          this.$message({
            type: 'warning',
            offset: 400,
            message: '折数只能为正数,且只能有一位小数'
          })
          return
        }
      } else {
        if (!String(this.sellingPrice)) {
          this.$message({
            type: 'warning',
            offset: 400,
            message: '定价不能为空'
          })
          return
        }
      }

      this.$confirm(
        '此操作将修改当前整页的' + this.type + ', 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          if (this.type == '定价') {
            this.costList.forEach((element) => {
              element.costOne = this.sellingPrice
            })
            putCostSave(
              JSON.stringify({
                kindsNumberList: this.costList,
                type: 0
              })
            ).then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this._getCost()
              } else {
                this.$message.error('修改失败')
              }
            })
          } else if (this.type == '折数') {
            this.costList.forEach((element) => {
              element.discount = this.discount
            })
            putCostSave(
              JSON.stringify({
                kindsNumberList: this.costList,
                type: 1
              })
            ).then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this._getCost()
              } else {
                this.$message.error('修改失败')
              }
            })
          } else if (this.type == '单款') {
            if (this.params.length == 0) {
              this.$message({
                type: 'warning',
                message: '请点击选中一条数据再进行修改单款定价的操作'
              })
            } else if (this.params.length == 1) {
              this.params[0].costOne = this.sellingPrice
              putCostSave(
                JSON.stringify({ kindsNumberList: this.params, type: 0 })
              ).then((res) => {
                if (res.data.code == 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  this._getCost()
                } else {
                  this.$message.error('修改失败')
                }
              })
              this.params = []
            }
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          })
        })
    },
    refresh() {
      var List = []
      this.costList.forEach((e) => {
        // console.log(e.costOne)
        if (e.costOne != null) {
          List.push(e)
        }
      })
      // console.log(JSON.stringify(List),'putCostUpdateputCostUpdateputCostUpdate')
      putCostUpdate(JSON.stringify(List)).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: '更新成功',
            type: 'success'
          })
        } else {
          this.$message.error('更新失败')
        }
      })
    },
    _getCost() {
      this.params = []
      let searchParams = {
        brandedName: this.brandedName,
        styleNumber: this.styleNumber,
        commodityName: this.commodityName,
        'pageData.limit': this.limit,
        'pageData.page': this.currentPage,
        groupByStyleNumber: this.showType == 1 ? true : false,
        // 新增
        newStyleNumber: this.newStyleNumber,
        quarter: this.quarter,
        quarterName: this.quarterName
      }
      // 查询参数要有值，删除没值的属性
      // 如果传的是空对象则查询出所有数据
      if (this.brandedName == '') {
        delete searchParams.brandedName
      }
      if (this.styleNumber == '') {
        delete searchParams.styleNumber
      }
      if (this.commodityName == '') {
        delete searchParams.commodityName
      }
      getCost(searchParams).then((res) => {
        this.dataLen = res.data.total
        this.costList = res.data.data
        console.log(res.data.data, '成本建档')
        this.costList.forEach((e) => {
          e.initialCostOne = e.costOne
        })
        this.costList.sort((a, b) => {
          if (a.styleNumber == b.styleNumber) {
            if (a.colorNo == b.colorNo) {
              return a.relevanceSize.localeCompare(b.relevanceSize)
            } else {
              return a.colorNo.localeCompare(b.colorNo)
            }
          } else {
            return a.styleNumber.localeCompare(b.styleNumber)
          }
        })
        // this.brandedName = ''
        // this.styleNumber = ''
        // this.commodityName = ''
        // this.discount = ''
        // this.sellingPrice = ''

        let imp = [this.costList[0]]
        let has = 0
        if (this.showType == '1') {
          for (const i of this.costList) {
            for (const j of imp) {
              if (i.styleNumber == j.styleNumber) {
                has = 0
                break
              }
              has = 1
            }
            if (has) imp.push(i)
          }
          this.showList = imp
          this.tableLabel = '款号'
          this.tableProp = 'styleNumber'
        } else if (this.showType == '2') {
          this.tableLabel = '货号'
          this.tableProp = 'kindsNumber'
          this.showList = this.costList
        } else if (this.showType == '3') {
          for (const i of this.costList) {
            for (const j of imp) {
              if (i.commodityName == j.commodityName) {
                has = 0
                break
              }
              has = 1
            }
            if (has) imp.push(i)
          }
          // console.log(this.showList, ' this.showList ')
          this.showList = imp
          this.tableLabel = '品名'
          this.tableProp = 'commodityName'
        }
      })
    },

    handleInputBlurResult(e, { index, key, result, row }) {
      // console.log(e)
      let r = /^(([0-9]|([1-9][0-9]{0,9}))((\.[0-9]{1,2})?))$/
      if (!r.test(result) && result) {
        this.$message.error('成本格式不合法')
        this.showList[index][key] = row.initialCostOne
        return
      }
      if (result == row.initialCostOne) return
      if (this.showType == '1') {
        // 款号
        getArtNo({
          styleNumber: row.styleNumber,
          pageSize: 9999,
          groupType: 1
        })
          .then((res) => {
            res.data.data.forEach((e) => {
              e.costOne = result
            })
            console.log(row, 'res.data.data')
            return putCostSave(
              JSON.stringify({ kindsNumberList: res.data.data, type: 0 })
            )
          })
          .then((r) => {
            if (r.data.code == 200) {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this._getCost()
            } else {
              this.$message.error('修改失败')
            }
          })
      } else {
        putCostSave(JSON.stringify({ kindsNumberList: [row], type: 0 })).then(
          (res) => {
            if (res.data.code == 200) {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this._getCost()
            } else {
              this.$message.error('修改失败')
            }
          }
        )
      }
      return
    },

    // 每页显示页数改变
    handleSizeChange(val) {
      this.limit = val
      this.currentPage = 1
      this.tableTypeChange = !this.tableTypeChange
      this._getCost()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this._getCost()
    },
    // 获取季度
    async getQuarter() {
      const { data } = await getQuarter()
      if (data && data.code === 200) {
        this.quarterList = data.data
      }
      // console.log(this.quarterList, '获取季度')
    },
    // 选择季度
    changeQuarterName(index) {
      let item = this.quarterList[index]
      this.quarter = item.id
      this.quarterName = item.name
    }
  },
  created() {
    // 获取季度
    this.getQuarter()
    this.inpList = this.getInput()
    getCommodityName({ limit: 99999 }).then((res) => {
      let list = res.data.data
      for (const item of list) {
        this.commodityNameList.push({ lable: item.name, value: item.name })
      }
    })
    // 品牌公司列表赋值
    getBranded({ limit: 99999 }).then((res) => {
      let list = res.data.data
      list.forEach((e) => {
        this.brandedNameList.push({ value: e.name, label: e.name })
      })
    })
  }
}
</script>

<style scoped>
.costDoc {
  margin-right: 0.5vw;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}

/* 头部 */
.topbar {
  /* height: 60px; */
  display: flex;
  /* overflow: hidden; */
  flex-wrap: wrap;
  /* white-space: nowrap; */
  border-bottom: 2px solid #f4f4f4;
}
.topbar p {
  width: auto;
  line-height: 60px;
  margin-right: 10px;
}

/* 按钮 */
.operation {
  padding: 15px 0;
  white-space: nowrap;
}
.operation i {
  color: #017aff;
  position: relative;
  right: -1090px;
}
.operation p {
  display: inline-block;
  position: relative;
  right: -1100px;
}

.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
</style>

<style>
.costDoc .topbar .el-input {
  margin: 15px 16px 0 0;
  height: 30px;
  width: 150px;
}
.costDoc .el-input__inner {
  height: 30px;
}
.costDoc .el-input__icon {
  line-height: 13px;
}
.costDoc .el-select {
  width: 150px;
  margin-right: 16px;
}
.costDoc .topbar .el-button {
  padding: 0 15px;
  height: 35px;
  margin-top: 13px;
}
.costDoc .el-button {
  padding: 8px 15px;
  margin-right: 12px;
  height: 30px;
}
.costDoc .el-button + .el-button {
  margin-left: 0;
}
.costDoc .el-icon-question:before {
  color: #017aff;
  position: relative;
  left: 0px;
  top: 0px;
}
</style>
